package com.example.geekbanglinkedlist;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zoRRo
 * @date 2020/11/14
 **/
public class Main {
    
    public static void main(String[] args) {
        
        // 初始化链表
        Linked<Integer> n = initLinked(20);
        Linked<Integer> m = initLinked(50);
        
        int result = compare(n, m);
        if (result == 999999) {
            System.out.println("未找到匹配项");
        } else {
            System.out.println("匹配项：" + result);
        }
    }
    
    /**
     * 遍历链表进行值比较
     *
     * @param n 链表
     * @param m 链表
     * @return 结果
     **/
    private static int compare(Linked<Integer> n, Linked<Integer> m) {
        int result = 999999;
        
        Map map = new HashMap<>();
        
        while (n != null) {
            map.put(n.val, "");
            n = n.getNext();
        }
        
        while (m != null) {
            if (map.get(m.val) != null) {
                result = m.val;
                break;
            }
            m = m.getNext();
        }
        
        return result;
    }
    
    
    /**
     * 初始化链表
     *
     * @param size 数量
     * @return 链表
     **/
    private static Linked<Integer> initLinked(int size) {
        Linked<Integer> linked = new Linked((int) (Math.random() * 100));
        int i = 0;
        while (i < size) {
            linked.add((int) (Math.random() * 100));
            i++;
        }
        System.out.println("---链表信息---");
        linked.print();
        System.out.println();
        return linked;
    }
}
